#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2020 Huawei Technologies Co., Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import sys
from queue import Queue
import acl
sys.path.append("..")
from base.dvpp import DvppInfo, AscendDvpp, AscendVdec
from resource.resource import ascend_resource
from common import const
from common.log import Log, check_ret


class PreProcess():
    def __init__(self, context, stream, conf_dict: dict):
        self.class_name = self.__class__.__name__
        self.context = context
        self.stream = stream
        self.memory_pool = ascend_resource.memory_pool
        if conf_dict['dvpp']:
            self.model_input_height = conf_dict['dvpp'][0]
            self.model_input_width = conf_dict['dvpp'][1]
            self.dvpp = AscendDvpp(context, stream)
        if conf_dict['vdec']:
            self.q_vdec = Queue(maxsize=50)
            self.channel_id = conf_dict['vdec'][0]
            self.encode_type = conf_dict['vdec'][1]
            self.pic_format = conf_dict['vdec'][2]
            self.vdec = AscendVdec(context, stream,
                            self.channel_id,
                            self.encode_type,
                            self.pic_format,
                            self.q_vdec)

    def get_dvpp(self):
        return self.dvpp
    
    def get_vdec(self):
        return self.vdec

    def run_preprocess(self, frame_data: DvppInfo):
        if self.vdec is None or self.dvpp is None:
            check_ret(self.class_name, 'run_preprocess', \
                'vdec:{}  dvpp:{}'.format(self.vdec, self.dvpp), 1)
        # vdec
        self.vdec.imread(frame_data, data_from='DEVICE')
        if self.q_vdec.empty():
            Log.do_log(const.WARNING, self.class_name,\
                    'pre_process', 'q_vedc is empty')
            return None, None
        # vdec image
        vdec_yuv_device = self.q_vdec.get()
        # ref image for postprocess
        vdec_yuv_ref = DvppInfo(vdec_yuv_device)
        # dvpp: resize --> crop --> paste
        resize_yuv_device = \
            self.dvpp.resize_crop_paste_with_same_ratio(vdec_yuv_device, 
                                                    self.model_input_width, 
                                                    self.model_input_height, 
                                                    vdec_yuv_device.pic_format)
        return vdec_yuv_ref, resize_yuv_device

    def release_preprocess(self):
        if self.vdec:
            self.vdec.destroy_resource(self.context)
            for _ in range(0, self.q_vdec.qsize()):
                data = self.q_vdec.get()
                self.memory_pool.release_memory(data.buffer_ptr, const.DVPP)
        if self.dvpp:
            self.dvpp.free_dvpp(self.context)
